package com.link.serve.tcp.process;

import com.link.serve.constants.ChannelAttrKey;
import com.link.serve.kafka.producer.KafkaMessageProducer;
import com.link.serve.tcp.linkdata.SingleUserChannelManager;
import com.link.serve.tcp.message.Message;
import com.link.serve.tcp.message.proto.PackHeader;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import static com.link.serve.constants.ChannelAttrKey.HEARTBEAT_TIMES;
import static com.link.serve.type.IMCmdType.LOGIN;
import static com.link.serve.utils.MessageUtils.buildResponseMessage;
import com.link.serve.constants.RedisOperatorConstant;

/**
 * 登录消息 发送这里要验证一次jwt
 * @Author: 杰
 * @Project :net-disk
 * @DateTime: 2024/7/2 14:30
 **/
@Slf4j
@Component
public class LoginProcessor extends AbstractMessageProcessor<Message>{
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private KafkaMessageProducer kafkaMessageProducer;

    @Override//客户端接收登录消息的处理器
    public void process(ChannelHandlerContext ctx,Message msg) throws ClassNotFoundException {
        PackHeader.Header header = msg.getHeader();
        // 绑定用户和channel
        SingleUserChannelManager.addChannel(header.getUid(), ctx);
        // 设置用户id属性
        AttributeKey<Long> userIdAttr = AttributeKey.valueOf(ChannelAttrKey.USER_ID);
        ctx.channel().attr(userIdAttr).set(header.getUid());
        // 初始化心跳次数
        AttributeKey<Long> heartBeatAttr = AttributeKey.valueOf(HEARTBEAT_TIMES);
        ctx.channel().attr(heartBeatAttr).set(0L);
        // 在redis上记录每个user的channelId，15秒没有心跳，则自动过期
        kafkaMessageProducer.sendRedisMessage(header, RedisOperatorConstant.LOGIN, RedisOperatorConstant.LOGIN);
        // 响应tcp
        log.info("user:{}_login_✅", header.getUid());
        Message response = buildResponseMessage(header.getAppId(), header.getUid(), "登录连接成功", LOGIN.code());
        ctx.writeAndFlush(response); // 将响应消息写回客户端
    }
}
